package com.podmanager.audio;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.view.KeyEvent;

public class MusicIntentReceiver extends BroadcastReceiver {
    public MusicIntentReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(AudioManager.ACTION_AUDIO_BECOMING_NOISY)) {
	        MusicService.doStartMusicService(context, MusicService.ACTION_PAUSE, null);
        }
        else if (intent.getAction().equals(MusicService.ACTION_KILL))
        {	  
    		MusicService.doStartMusicService(context, MusicService.ACTION_KILL, null);
        }
        else if (intent.getAction().equals(Intent.ACTION_MEDIA_BUTTON))
        {	    	
        	final KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);

    	//event doesn't occur for all of the intent actions that I listed
    	//exit if we don't get an event
	    	if (event ==null)return;
    	//I chose to respond to down presses only, could also respond to ACTION_UP
	    	if (event.getAction() != KeyEvent.ACTION_DOWN) return;
	    	
	        switch (event.getKeyCode()) {
		    	case KeyEvent.KEYCODE_MEDIA_NEXT:
		    		MusicService.doStartMusicService(context, MusicService.ACTION_FFWD, null);
		           	break;
	           	case KeyEvent.KEYCODE_MEDIA_PLAY:
	           	case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
	           	case KeyEvent.KEYCODE_MEDIA_PAUSE:
		    		MusicService.doStartMusicService(context, MusicService.ACTION_PLAYPAUSE, null);
		    		break;
	           	case KeyEvent.KEYCODE_HEADSETHOOK:
	           	case KeyEvent.KEYCODE_MEDIA_STOP:
		    		MusicService.doStartMusicService(context, MusicService.ACTION_STOP, null);
	               	break;
	           	case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
		    		MusicService.doStartMusicService(context, MusicService.ACTION_REWIND, null);
	               	break;
	        }
        }
    }
}
